//
//  AgencyEntryView.m
//  Portable Traffic Signal Assistor
//
//  Created by Hao Xu on 4/13/12.
//  Copyright (c) 2012 TTU. All rights reserved.
//

#import "AgencyEntryView.h"

@interface AgencyEntryView ()

@end

@implementation AgencyEntryView
@synthesize sections=_sections;
@synthesize  agencyNameSection=_agencyNameSection;
@synthesize agencySection=_agencySection;
@synthesize assistingToolsSection=_assistingToolsSection;
@synthesize addAgencyButton=_addAgencyButton;
@synthesize agencyList=_agencyList;
@synthesize publicSender=_publicSender;
@synthesize agencyDetailViewController=_agencyDetailViewController;
@synthesize imageView=_imageView;
@synthesize gpsRecordViewController=_gpsRecordViewController;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) dealloc
{
    [_sections release];
    [_agencyNameSection release];
    [_agencySection release];
    [_assistingToolsSection release];
    [_addAgencyButton release];
    [_agencyList release];
    [_agencyDetailViewController release];
    [_imageView release];
    [_gpsRecordViewController release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [XMLParser loadDataXML];
//    self.tableView.backgroundColor = [UIColor colorWithRed:0 green:0.18 blue:0.384 alpha:1];
    self.tableView.backgroundColor = [UIColor clearColor];
    UIImageView *backgroundView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]] autorelease];

    [self.navigationController.view addSubview:backgroundView];
    [self.navigationController.view sendSubviewToBack:backgroundView];
    self.tableView.opaque = NO;
    self.tableView.backgroundView = nil;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    UIImageView *unrLogoImageView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"UNRLogo.png"]] autorelease];
    unrLogoImageView.frame=CGRectMake(60, 10, 160, 50);
    [self.tableView addSubview:unrLogoImageView];
    
    UIImageView *nameImageView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Name2.png"]] autorelease];
    nameImageView.frame=CGRectMake(10, 70, 300, 50);
    [self.tableView addSubview:nameImageView];
    
//    CGPoint offset;
//    offset.x=0;
//    offset.y=-100;
//    self.tableView.contentOffset=offset;
//    float yOffset = 50.0f; // Change this how much you want!
//    self.tableView.frame =  CGRectMake(self.tableView.frame.origin.x, self.tableView.frame.origin.y + yOffset, self.tableView.frame.size.width, self.tableView.frame.size.height);

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    if (!_agencyNameSection) {
        _agencyNameSection=[[TableSection alloc]init];
//        _agencyNameSection.contents=[[[NSMutableArray alloc] initWithObjects:@"", nil] autorelease];
        _agencyNameSection.header=@"   \n  \n  \n  \n ";
    }
    if(!_agencySection)
    {
        _agencySection=[[TableSection alloc]init];
        self.agencyList=[XMLParser getAgencyList];
//        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _agencySection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.agencyList.count; i++) {
            [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
        }
        
        _agencySection.header=@"Agency List";
    }
    if(!_assistingToolsSection)
    {
        _assistingToolsSection=[[TableSection alloc]init];
//        self.agencyList=[XMLParser getAgencyList];
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _assistingToolsSection.contents=[[[NSMutableArray alloc] init] autorelease];
        [_assistingToolsSection.contents addObject:@"GPS Recorder"];
//        for (int i=0; i<self.agencyList.count; i++) {
//            [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
//        }
        
        _assistingToolsSection.header=@"Assisting Tools";
    }
    if (!_sections) {
        _sections = [[NSMutableArray alloc] init];
        [_sections addObject:_agencyNameSection];
        [_sections addObject:_agencySection];
        [_sections addObject:_assistingToolsSection];
    }
//    if(!_addAgencyButton)
//    {
//        _addAgencyButton=[UIButton buttonWithType:UIButtonTypeContactAdd];
////        [_addAgencyButton setFrame:CGRectMake(300-80,((40-24)/2),80,24)];
////        [_addAgencyButton setTitle:@"Remove" forState:UIControlStateNormal];
//        [_addAgencyButton addTarget:self action:@selector(clickAddAgencyButton:) 
//                       forControlEvents:UIControlEventTouchUpInside];
//        
//    }
    if (!_imageView) {
        _imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_title.png"]];
    }
  
//    self.navigationItem.titleView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_title.png"]] autorelease];
//    [self.navigationController.navigationBar addSubview:self.imageView];
    [self.navigationController setNavigationBarHidden:NO];
    
//    UIBarButtonItem            *buttonItem;
    
//    buttonItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Map"
//                                                    style: UIBarButtonItemStyleBordered
//                                                   target: self
//                                                   action: @selector( goToMap:) ];
//    self.toolbarItems = [ NSArray arrayWithObject: buttonItem ];
//    [ buttonItem release ];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.sections=nil;
    self.agencyNameSection=nil;
    self.agencySection=nil;
    self.assistingToolsSection=nil;
    self.addAgencyButton=nil;
    self.agencyList=nil;
    self.agencyDetailViewController=nil;
    self.imageView=nil;
    self.gpsRecordViewController=nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self.navigationController setNavigationBarHidden:YES animated:YES];
//    [self.navigationController.navigationBar addSubview:self.imageView];
//    self.navigationItem.titleView=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo_title.png"]] autorelease];
    self.navigationItem.title=@"";
    self.agencySection.contents=[[[NSMutableArray alloc] init] autorelease];
    for (int i=0; i<self.agencyList.count; i++) {
        [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
    }
    [self.navigationController setToolbarHidden:YES];
    [self.navigationController setNavigationBarHidden:YES];
//    CGRect myRect = [self.tableView frame]; // a new rectangle object
//    myRect.origin.x = 0;
//    myRect.origin.y = 100;
//    [self.tableView setFrame:myRect];
[self.tableView reloadData];
    
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    // Return the number of sections.
    return [self.sections count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    // Return the number of rows in the section.
    NSArray *sectionContents=[[self.sections objectAtIndex:section] contents];
    
    return [sectionContents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    
    
    TableSection *section=[self.sections objectAtIndex:indexPath.section];
    NSArray *sectionContents=[section contents];
    NSString *sectionContentString=[sectionContents objectAtIndex:indexPath.row];
    
    
    [cell setAccessoryType:[section accessoryType]];
    cell.textLabel.numberOfLines=0;
    cell.textLabel.lineBreakMode=UILineBreakModeWordWrap;    
    cell.textLabel.text=sectionContentString;
    if (indexPath.section==1) {
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }else
    {
        UIImageView *GPSimage=[[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"GPS_icon.png"]] autorelease];
        GPSimage.frame=CGRectMake(250, 1, 44, 44);
        [cell addSubview:GPSimage];
        [cell setBackgroundColor:[UIColor lightGrayColor]];
    }
    
//    if (indexPath.section==0) {
////        _agencyNameSection
//        cell.frame =  CGRectMake(0,50,320,50);
//        cell.opaque=YES;
//    }
    cell.opaque=NO;
    
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if (indexPath.section==0) {
        return 0;
    }else {
        return 44;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (section==0) {
        CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
        UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
        headerView.backgroundColor = [UIColor clearColor];
        UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
        aLabel.text =[[self.sections objectAtIndex:section] header] ;
        aLabel.numberOfLines=0;
        aLabel.lineBreakMode=UILineBreakModeWordWrap; 
        aLabel.font = [UIFont boldSystemFontOfSize:24.0];
        aLabel.textAlignment = UITextAlignmentCenter;
        aLabel.backgroundColor = [UIColor clearColor];
        aLabel.textColor=[UIColor darkGrayColor];
        
        
        [headerView addSubview:aLabel];
        return headerView;
    }
    
    CGRect headerViewRect = CGRectMake(0.0,0.0,320,40);
    UIView* headerView = [[[UIView alloc] initWithFrame:headerViewRect] autorelease];
    headerView.backgroundColor = [UIColor clearColor];
    UILabel *aLabel = [[[UILabel alloc] initWithFrame:CGRectMake(20,0.0,300,40)] autorelease];
    aLabel.text =[[self.sections objectAtIndex:section] header] ;
    aLabel.font = [UIFont boldSystemFontOfSize:16.0];
    aLabel.textAlignment = UITextAlignmentLeft;
    aLabel.backgroundColor = [UIColor clearColor];
    aLabel.textColor=[UIColor darkTextColor];
    
   
    [headerView addSubview:aLabel];
    
    if (section==1) {
        UIButton *newbutton=[UIButton buttonWithType:UIButtonTypeContactAdd];
        [newbutton setFrame:CGRectMake(120,4,30,30)];
        //    [newbutton setTitle:@"Remove" forState:UIControlStateNormal];
        //        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        [newbutton setTag:(section)];
        [newbutton addTarget:self action:@selector(clickAddAgencyButton:)
            forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:newbutton];
    }
    //Then you can add a UILabel to your headerView
    
    
    return headerView;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath 
{

    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) 
    {
        // Commit the delete
        [self removeAgency:indexPath.row];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    
    
    return [[self.sections objectAtIndex:section] header];
    
}
#pragma mark - AlertView delegate
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        // Launch nuclear strike !
        
//        NSArray *timerGroupList=[XMLParser getTimerGroupList];
        int tag=[self publicSender];
        [XMLParser removeAgency:[[self.agencyList objectAtIndex:tag] agencyID]];
        self.agencyList=[XMLParser getAgencyList];
        //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
        _agencySection.contents=[[[NSMutableArray alloc] init] autorelease];
        for (int i=0; i<self.agencyList.count; i++) {
            [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
        }
        
        [self.tableView reloadData];
    } else {
        // be nice with the world, maybe initiate some Ecological action as a bonus
    }
}

#pragma mark - Customized codes
- (void) clickAddTimerGroupButton
{
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    switch (indexPath.section) {
        case 1:
        {
            AgencyDetailViewController *detailViewController=[[[AgencyDetailViewController alloc] initWithNibNameAndAgency:@"AgencyDetailViewController" agency:[self.agencyList objectAtIndex:indexPath.row] bundle:nil] autorelease];
            //    self.navigationItem.titleView=nil;
            //    [self.imageView removeFromSuperview];
            self.navigationItem.title=@"Home";
            [detailViewController setTitle:@"Agency Detail"];
            [self.navigationController pushViewController:detailViewController animated:YES];
        }
            break;
        case 2:
        {
            if (!self.gpsRecordViewController) {
                self.gpsRecordViewController=[[[GPSRecorderViewController alloc] init] autorelease];
            }
            
            self.navigationItem.title=@"Home";
            [self.gpsRecordViewController setTitle:@"GPS Tool"];
            [self.navigationController pushViewController:self.gpsRecordViewController animated:YES];
        }
            
        default:
            break;
    }

    
//[self.navigationController setNavigationBarHidden:NO animated:YES];

//[[SignalAssistorDetailEditViewController alloc]initWithNibNameTimerGroupIDAndSignalID:@"SignalAssistorDetailEditViewController" timerGroupID:timerGroupIDString signalID:signalIDString bundle:nil] ;
}

#pragma mark - Customized functions
- (void) clickAddAgencyButton:(id)sender
{
    Agency * newAgency=[[[Agency alloc] init] autorelease];
    [newAgency setAgencyID:[XMLParser createAgencyID]];
    [newAgency setAgencyName:@"New Agency"];
    [XMLParser createAgency:newAgency];
    self.agencyList=[XMLParser getAgencyList];
    //        _agencySection.contents=[[[NSMutableArray alloc] initWithArray:[XMLParser getAgencyList]] autorelease];
    _agencySection.contents=[[[NSMutableArray alloc] init] autorelease];
    for (int i=0; i<self.agencyList.count; i++) {
        [_agencySection.contents addObject:[[self.agencyList objectAtIndex:i] agencyName]];
    }
    
    [self.tableView reloadData];
    
}

- (void) removeAgency:(int) row
{
    self.publicSender=row;
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirmation" 
                                                    message:@"Delete the agency and its signals?" 
                                                   delegate:self 
                                          cancelButtonTitle:@"YES"
                                          otherButtonTitles:@"NO",nil];
    [alert show];
    [alert release];
}

- (void) goToMap:(id)sender
{
    ExploreMapViewViewController *detailViewController=[[[ExploreMapViewViewController alloc] initWithNibName:@"ExploreMapViewViewController" bundle:nil] autorelease];
    //    self.navigationItem.titleView=nil;
//    [self.imageView removeFromSuperview];
//    self.navigationItem.title=@"Home";
    [detailViewController setTitle:@"Signal Map"];
    [self.navigationController pushViewController:detailViewController animated:YES];
}

@end
